package com.wsc.springbootmultidevdemo.msg.workq;

import com.rabbitmq.client.*;
import com.wsc.springbootmultidevdemo.msg.ConnectionUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * 消费者1 Fair dispatch 模式
 * 需将应答模式变为手动
 */
@Slf4j
public class Worker1 {

    private final static String QUEUE_NAME = "Work Queues";

    public static void main(String[] args) throws Exception {
        receive();
    }

    private static void receive() throws Exception{
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();
        channel.queueDeclare(QUEUE_NAME,false,false,false,null);

        //同一时刻只能发送一条消息给这个 worker
        channel.basicQos(1);

        //定义消费者订阅这个频道
        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                try {
                    doWork(message);
                    //手动应答
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        };

        //订阅消息 false 手动应答,需调用basicAck 来应答
        channel.basicConsume(QUEUE_NAME,false,consumer);

    }

    /**
     * 模拟处理数据时间
     * @param msg
     * @throws Exception
     */
    private static void doWork(String msg) throws Exception{
        System.out.println("[C] Receive "+msg+"is resolving  ");
        Thread.sleep(3000);
    }
}
